package com.czkt.config;

import com.czkt.pojo.SysRoleRight;
import com.czkt.pojo.vo.SysUserVo;
import com.czkt.service.ISysUserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.util.ByteUtils;

import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class MyShiroRealm extends AuthorizingRealm {
    @Autowired
    ISysUserService sysUserService;

    /**
     * 授权
     *
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("进入授权方法！！！！！！");

        SysUserVo sysUserVo = (SysUserVo) principalCollection.getPrimaryPrincipal();

        List<SysRoleRight> sysRoleRights = sysUserService.getSysRoleById(sysUserVo.getUsrRoleId());

        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();

        info.addStringPermissions(sysRoleRights.stream().map(roleRight -> roleRight.getRfRightCode()).collect(Collectors.toList()));

        return info;
    }

    /**
     * 认证
     *
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("进入认证方法！！！！！！");
        String usrName = (String) authenticationToken.getPrincipal();
        SysUserVo sysUserVo = sysUserService.getUserByName(usrName);
        if (sysUserVo == null) {
            throw new UnknownAccountException();//账号错误
        }
        if (sysUserVo.getUsrFlag() == null || sysUserVo.getUsrFlag().intValue() == 0) {
            throw new LockedAccountException();//账号不可用
        }
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(
                sysUserVo,
                sysUserVo.getUsrPassword(),
                ByteSource.Util.bytes("czkt"),//设置盐
                getName());

        return info;
    }
}
